package cn.tedu.fresheveryday.controller;

import cn.tedu.fresheveryday.pojo.entity.User;
import cn.tedu.fresheveryday.pojo.dto.UserLoginDTO;
import cn.tedu.fresheveryday.pojo.dto.UserRegisterDTO;
import cn.tedu.fresheveryday.restful.JsonResult;
import cn.tedu.fresheveryday.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@Api(tags = "用户模块")
@RequestMapping(path = "/user", produces = "application/json;charset=utf-8")
public class UserController {
    @Autowired
    private IUserService service;

    /**
     * 注册
     * @param userRegisterDTO
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public JsonResult<Void> reg(@RequestBody UserRegisterDTO userRegisterDTO) {
        service.reg(userRegisterDTO);

        return JsonResult.success();
    }

    /**
     * 登录
     * @param userLoginDTO
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public JsonResult<Void> login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session) {
        User user = service.login(userLoginDTO);

        session.setAttribute("user", user);

        return JsonResult.success();
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public JsonResult<Void> logout(HttpSession session) {
        User user = (User) session.getAttribute("user");

        if (user != null) {
            session.removeAttribute("user");

            return JsonResult.success();
        }

        return JsonResult.error("退出登录失败，您当前未登录。");
    }

    /**
     * 获取登录的用户信息
     * @param session
     * @return
     */
    @GetMapping("/getlogin")
    @ApiOperation("获取登录的用户信息")
    public User getLogin(HttpSession session) {
        return (User) session.getAttribute("user");
    }

}